public class MergeSort {
    public static void mergeSort(int[] array){
        mergeFunc(array,0, array.length-1);
    }

    private static void mergeFunc(int[] array, int left, int right) {
        if (left > right) {
            return;
        }
        int mid = left + ((right-left) >> 1);
        mergeFunc(array, left, mid);
        mergeFunc(array, mid+1, right);

        merge(array,left,mid,right);
    }

    private static void merge(int[] array, int mid, int left, int right) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid+1;
        int e2 = right;
        int[] tmpArr = new int[right-left+1];
        int k = 0;

        while (s1 <= e1 && s2 <= e2) {
            if (array[s1] <= array[s2]) {
                tmpArr[k++] = array[s1++];
            }else {
                tmpArr[k++] = array[s2++];
            }
        }

        while (s1 <= e1) {
            tmpArr[k++] = array[s1++];
        }
        while (s2 <= e2) {
            tmpArr[k++] = array[s2++];
        }

        for (int i = 0; i < k; i++) {
            array[i] = tmpArr[i];
        }
    }
}
